<template>
  <div class="workspace-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>教师工作区</span>
        </div>
      </template>

      <!-- 工作区列表 -->
      <el-table :data="workspaces" style="width: 100%">
        <el-table-column prop="course" label="课程" />
        <el-table-column prop="name" label="工作区名称" />
        <el-table-column prop="openai_history" label="历史记录上限" />
        <el-table-column prop="openai_temp" label="温度值" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleOpenSettings(scope.row)"
            >
              设置
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleOpenUpload(scope.row)"
            >
              上传文档
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleOpenDocuments(scope.row)"
            >
              查看文档
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 设置对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="工作区设置"
        width="500px"
      >
        <el-form
          ref="settingsForm"
          :model="currentSettings"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="历史记录上限" prop="openai_history">
            <el-input-number
              v-model="currentSettings.openai_history"
              :min="1"
              :max="100"
            />
          </el-form-item>
          <el-form-item label="温度值" prop="openai_temp">
            <el-slider
              v-model="currentSettings.openai_temp"
              :min="0"
              :max="1"
              :step="0.1"
              show-input
            />
          </el-form-item>
          <el-form-item label="系统提示词" prop="openai_prompt">
            <el-input
              v-model="currentSettings.openai_prompt"
              type="textarea"
              :rows="4"
              placeholder="请输入系统提示词"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleUpdateSettings">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 文件上传对话框 -->
      <el-dialog
        v-model="uploadDialogVisible"
        title="上传文档"
        width="500px"
      >
        <el-upload
          ref="uploadRef"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          multiple
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">请选择要上传的文档文件</div>
          </template>
        </el-upload>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="uploadDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="handleUploadFiles"
              :loading="uploading"
            >
              上传
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 文档列表对话框 -->
      <el-dialog
        v-model="documentsDialogVisible"
        title="工作区文档"
        width="800px"
      >
        <workspace-documents
          v-if="documentsDialogVisible"
          :workspace-id="currentWorkspaceId"
        />
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import WorkspaceDocuments from './WorkspaceDocuments.vue'

const props = defineProps({
  userInfo: {
    type: Object,
    required: true
  }
})

const loading = ref(false)
const workspaces = ref([])
const dialogVisible = ref(false)
const uploadDialogVisible = ref(false)
const documentsDialogVisible = ref(false)
const uploading = ref(false)
const currentSettings = ref({
  openai_history: 0,
  openai_temp: 0,
  openai_prompt: ''
})
const currentWorkspaceId = ref(null)
const uploadRef = ref(null)
const uploadFiles = ref([])

// 表单验证规则
const rules = {
  openai_history: [
    { required: true, message: '请输入历史记录上限', trigger: 'blur' },
    { type: 'number', min: 1, max: 60, message: '范围在 1 到 60 之间', trigger: 'blur' }
  ],
  openai_temp: [
    { required: true, message: '请设置温度值', trigger: 'blur' },
    { type: 'number', min: 0, max: 1, message: '范围在 0 到 1 之间', trigger: 'blur' }
  ],
  openai_prompt: [
    { required: true, message: '请输入系统提示词', trigger: 'blur' }
  ]
}

// 获取工作区列表
const fetchWorkspaces = async () => {
  try {
    loading.value = true
    const response = await axios.get('/backend/api/llm/workspaces/')
    workspaces.value = response.data
  } catch (error) {
    ElMessage.error('获取工作区列表失败')
    console.error('获取工作区列表错误:', error)
  } finally {
    loading.value = false
  }
}

// 打开设置对话框
const handleOpenSettings = (workspace) => {
  currentWorkspaceId.value = workspace.id
  currentSettings.value = {
    openai_history: workspace.openai_history,
    openai_temp: workspace.openai_temp,
    openai_prompt: workspace.openai_prompt
  }
  dialogVisible.value = true
}

// 更新设置
const handleUpdateSettings = async () => {
  try {
    const response = await axios.patch(
      `/backend/api/llm/workspace/${currentWorkspaceId.value}/settings/`,
      currentSettings.value
    )

    if (!response || !response.data) {
      throw new Error('更新响应数据无效')
    }

    ElMessage.success('设置更新成功')
    dialogVisible.value = false

    // 更新列表中的数据
    const index = workspaces.value.findIndex(w => w.id === currentWorkspaceId.value)
    if (index !== -1) {
      workspaces.value[index] = {
        ...workspaces.value[index],
        ...response.data
      }
    }
  } catch (error) {
    let errorMessage = '更新设置失败'

    if (error.response && error.response.data) {
      const errorDetails = Object.values(error.response.data)
      if (errorDetails.length > 0) {
        errorMessage = errorDetails.join('\n')
      }
    }

    ElMessage.error(errorMessage)
    console.error('更新设置错误:', error)
  }
}

// 打开上传对话框
const handleOpenUpload = (workspace) => {
  currentWorkspaceId.value = workspace.id
  uploadFiles.value = []
  uploadDialogVisible.value = true
}

// 打开文档列表对话框
const handleOpenDocuments = (workspace) => {
  currentWorkspaceId.value = workspace.id
  documentsDialogVisible.value = true
}

// 处理文件选择变化
const handleFileChange = (file) => {
  uploadFiles.value.push(file)
}

// 处理文件移除
const handleFileRemove = (file) => {
  const index = uploadFiles.value.findIndex(f => f.uid === file.uid)
  if (index !== -1) {
    uploadFiles.value.splice(index, 1)
  }
}

// 处理文件上传
const handleUploadFiles = async () => {
  if (uploadFiles.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  try {
    uploading.value = true
    const formData = new FormData()
    uploadFiles.value.forEach(file => {
      formData.append('files', file.raw)
    })

    const response = await axios.post(
      `/backend/api/llm/workspace/${currentWorkspaceId.value}/documents/`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )

    if (response.data.success.length > 0) {
      ElMessage.success('文档上传成功')
      uploadDialogVisible.value = false
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
      uploadFiles.value = []
    }

    if (response.data.failed.length > 0) {
      ElMessage.warning(`${response.data.failed.length}个文件上传失败`)
    }
  } catch (error) {
    ElMessage.error('文档上传失败')
    console.error('上传文档错误:', error)
  } finally {
    uploading.value = false
  }
}

onMounted(() => {
  fetchWorkspaces()
})
</script>

<style scoped>
.workspace-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-slider) {
  width: 100%;
}

.el-upload__tip {
  margin-top: 8px;
  color: #909399;
}
</style>